<?php
namespace app\admin\model;
use think\Model;


class Distributor extends BaseModel {
    
   
    /**
     * 数据表主键
     * @var string
     */

    protected $pk = 'id';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    
     /**
     * 模型名称
     * @var string
     */
    protected $name = 'distributor';

    public function getStatusNameAttr($value,$data){
        $type = [0=>'待审核',1=>'审核通过',2=>'审核拒绝'];
        return $type[$data['status']];
    }



    
        /**
     * 检查是否是分销员
     */
    public static function checkDistributor($did){
        if(!$did){
            return false;
        }
        if(!$Distributor = self::find($did)){
            return false;
        }
        if($Distributor->status !=1 ){
            return false;
        }
        return true;
    }


        /**
     * 佣金入账
     * @return void
     * @author Sam
     * @date 2022-02-16
     */
    public static function income($uid,$balance,$type = 1){
        $user = User::find($uid);
        $dis_user = self::where('id',$user->did)->lock(true)->find();
        if($dis_user->status ==1 && $balance > 0){
            $dis_user->balance += $balance;
            $res1 =  $dis_user->save();
            $res2 = BalanceLog::create([
                'uid' => $uid,
                'amount' => $balance,
                'type'   => $type,
                'spec'   => 1,
                'did'   => $dis_user->id,
                'source' => 1
            ]);
            if($res1 && $res2){
                return true;
            }else{
                return false;
            }
        } 
        return false;
    }

        /**
     * 佣金出账
     * @return void
     * @author Sam
     * @date 2022-02-16
     */
    public static function outcome($uid,$balance){
        $user = User::find($uid);
        $dis_user = self::where('id',$user->did)->lock(true)->find();
        if($dis_user->status == 1 && $balance > 0 && $dis_user->balance >=$balance){
            $dis_user->balance -= $balance;
            $res1 = $dis_user->save();
            $res2 = BalanceLog::create([
                'uid' => $uid,
                'amount' => $balance,
                'type'   => 3,
                'spec'   => 2,
                'did'   => $dis_user->id,
                'source' => 1,

            ]);
            if($res1 && $res2){
                return true;
            }else{
                return false;
            }
        } 
        return false;
    }
}

